package com._4pd.demo.formal.template;

import com._4pd.demo.formal.crd.AiOperator;
import com._4pd.demo.formal.crd.AiOperatorSpec;
import com._4pd.demo.formal.crd.Algorithm;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.tree.parse.DefaultTokenScannerSymbols;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JinJaRender implements AiTemplateRender{
    protected Jinjava jinjava;
    public JinJaRender(){
        this.jinjava = new Jinjava();
        // 修改模版表达式，避免与argo表达式冲突
        this.jinjava.getGlobalConfig().setTokenScannerSymbols(new DefaultTokenScannerSymbols(){
            public char getExprStartChar() {
                return '*';
            }
            public char getExprEndChar() {
                return '*';
            }
        });

    }

    @Override
    public String render(AiOperator resource) throws Exception {
        AiOperatorSpec aiOperatorSpec = resource.getSpec();
//        String spec_json_str = JSONObject.toJSONString(resource.get("spec"));
//        AiOperatorSpec aiOperatorSpec = JSONObject.parseObject(spec_json_str, AiOperatorSpec.class);
        // 读取根数据
        Map<String,Object> root = new HashMap<>();
        root.put("Kind",resource.getKind());
        root.put("ApiVersion",resource.getApiVersion());
        root.put("Metadata",resource.getMetadata());
        root.put("name","operator-"+resource.getMetadata().getName()+"");

        // 构造数据
        Map<String, Object> data = new HashMap<>();
        data.put("root", root);
        data.put("run_params", aiOperatorSpec);

        // 获取模版
        Algorithm algorithm = aiOperatorSpec.getAlgorithm();

        String template = Resources.toString(Resources.getResource("jinja/"+algorithm.getType()+".yaml"), Charsets.UTF_8);

        String renderedTemplate = jinjava.render(template, data);
        return renderedTemplate;
    }

    public static void main(String[] args) throws Exception {
        String render = new JinJaRender().render(null);
        System.out.println(render);
    }
}
